﻿using AutoMapper.Execution;
using MediatR;
using T_Person.BaseRep.Interface;
using T_Person.Read.APi.Applaction.Command.TotalPersonnel;
using T_Person.Read.APi.Dto;

namespace T_Person.Read.APi.Applaction.CommandHandlers.TotalPersonnelHandlers
{
    public class TotalPersonnelSeniorHandlers : IRequestHandler<TotalPersonnelSeniorityCommand, List<PersonnelAgeGroup>>
    {
        private readonly IEmployeeRep employeeRep;

        public TotalPersonnelSeniorHandlers(IEmployeeRep employeeRep)
        {
            this.employeeRep = employeeRep;
        }

        public async Task<List<PersonnelAgeGroup>> Handle(TotalPersonnelSeniorityCommand request, CancellationToken cancellationToken)
        {
            var list = await employeeRep.GetvaluesByResult(x => !x.IsDel&&x.EmployeeStyle>0);
            int listcount = list.Count();
            var agelist = list.ToArray().GroupBy(x =>
            {
                var ages = Getage(x.EntrtDate);
                if (ages >= 1 && ages <= 3) return "1-3年";
                if (6 >= ages && ages >= 4) return "4-6年";
                if (9 >= ages && ages >= 7) return "7-9年";
                if (ages >= 10) return "10年以上";
                return "无工龄";
            }).Select(x=>new PersonnelAgeGroup
            {
                name=x.Key,
                number= Math.Round(((double)x.Count()) / listcount * 100, 2)
            }).ToList();
            return agelist;
        }

        public static int Getage(DateTime? dateTime)
        {
            DateTime date = Convert.ToDateTime(dateTime);
            if (date.Year<10)
            {
                return 0;
            }
            
            int age= DateTime.Now.Year-date.Year;
            if (age<1)
            {
                return 1;
            }
            return age;
        }
    }
}
